package com.grayscale.core.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;


/**
 * 本地缓存文件
 * @author liuli
 * @date 2022/2/25
 */
public class GrayScaleOfflineUtil {
    private static final Logger logger = LoggerFactory.getLogger(GrayScaleOfflineUtil.class);

    /***
     * 创建文件并写入
     * @param filePath
     * @param data
     * @param update
     */
    public static void writeDisk(String filePath,String data,Boolean update) {
        BufferedWriter out = null;
        try {
            File outputFile = new File(filePath);
            File fileParent = outputFile.getParentFile();
            if(!fileParent.exists()){
                fileParent.mkdirs();
            }
            if (!outputFile.exists()){
                outputFile.createNewFile();
            }
            if (update){
                 out = new BufferedWriter(new FileWriter(outputFile));
                if (data ==null){
                    out.write("");
                }else{
                    out.write(data);
                }
                out.close();
                logger.info("Write local:{} data:{}",filePath,data);
            }
        } catch (Exception e) {
            logger.error("Write local error..", e.getMessage());
        }finally {
           if (out != null){
               try {
                   out.close();
               } catch (IOException e) {
               }
           }
        }
    }

    /***
     * 读取文件
     * @param filePath
     * @return
     */
    public static String readDisk(String filePath) {
        BufferedReader bufferedReader = null;
        try {
            File outputFile = new File(filePath);
            if (!outputFile.exists()){
                return null;
            }
            bufferedReader = new BufferedReader(new FileReader(filePath));
            String s;
            StringBuffer sb = new StringBuffer();
            while((s=bufferedReader.readLine()) != null){
                sb.append(s);
            }
            bufferedReader.close();
            return sb.toString();
        } catch (IOException e) {
            logger.error("Read local error..", e.getMessage());
            return null;
        }finally {
            if (bufferedReader != null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                }
            }
        }
    }

}
